/* eslint-disable max-lines */
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Table, Divider } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid } from '../stores/definitions_theme';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import { ColorSelector } from 'color-selector-react';
import 'color-selector-react/dist/es/index.css';
import styles from './Theme.module.scss';
import ChargeForm from './ChargeForm';

const FromItem = Form.Item;

const Theme = ({ modal, onCancel, onSubmit }) => {
  const { xcxStore: store } = useStore();
  // 使用useRef进行拼接字段且不会造成重绘
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const [theme] = useState(() => observable({}));
  const [color, setColor] = useState('');
  const [state, setState] = useState({
    sc: [],
    bus: [],
    rsPlay: [],
    rsDetail: [],
  });
  const [idx, setIdx] = useState({
    sc: -1,
    bus: -1,
    rsPlay: -1,
    rsDetail: -1,
  });
  const [curCharge, setCurCharge] = useState();
  const [visible, setVisible] = useState(false);

  useEffect(() => { if (modal[1]?.startsWith?.('toClose') || modal[2]?.startsWith?.('toClose')) handleCancel(); }, [modal]);
  useEffect(() => {
    (async () => {
      const res = await store.getDict('appConfigs');
      const data = res.find((p) => p.itemId === 'busThemes');
      const themeColor = data.extras?.themeColor?.value;
      editCtx.origin = _.cloneDeep(data);
      const parseSc = JSON.parse(data.extras?.scPropagationLanguage?.value || '[]');
      const parseBus = JSON.parse(data.extras?.busPropagationLanguage?.value || '[]');
      const parseRsPlay = JSON.parse(data.extras?.rsPlayOrderCautionLanguage?.value || '[]');
      const parseRsDetail = JSON.parse(data.extras?.rsOrderDetailCautionLanguage?.value || '[]');
      setState({
        sc: parseSc,
        bus: parseBus,
        rsPlay: parseRsPlay,
        rsDetail: parseRsDetail,
      });
      _.assign(theme, data);
      _.set(theme, 'extras.themeColor.value', themeColor);
      setColor(themeColor);
    })();
  }, []);

  const scColumns = [
    {
      title: t`序号`,
      dataIndex: 'id',
      align: 'center',
      cell: (v, i) => <span>{i + 1}</span>,
    },
    {
      title: t`宣传语`,
      dataIndex: 'name',
      width: 200,
      align: 'center',
    },
    {
      title: t`操作`,
      dataIndex: 'name',
      align: 'center',
      cell: (v, i, r) => (
        <>
          <Button type="primary" text onClick={() => handleCurCharge(r, 'sc')}>{t`编辑`}</Button>
          <Divider direction="ver" />
          <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeleteState(i, 'sc')}>{t`删除`}</Button>
        </>
      ),
    },
  ];
  const busColumns = [
    {
      title: t`序号`,
      dataIndex: 'id',
      align: 'center',
      cell: (v, i) => <span>{i + 1}</span>,
    },
    {
      title: t`宣传语`,
      dataIndex: 'name',
      width: 200,
      align: 'center',
    },
    {
      title: t`操作`,
      dataIndex: 'name',
      align: 'center',
      cell: (v, i, r) => (
        <>
          <Button type="primary" text onClick={() => handleCurCharge(r, 'bus')}>{t`编辑`}</Button>
          <Divider direction="ver" />
          <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeleteState(i, 'bus')}>{t`删除`}</Button>
        </>
      ),
    },
  ];
  const rsPlayColumns = [
    {
      title: t`序号`,
      dataIndex: 'id',
      align: 'center',
      cell: (v, i) => <span>{i + 1}</span>,
    },
    {
      title: t`事项`,
      dataIndex: 'name',
      width: 200,
      align: 'center',
    },
    {
      title: t`操作`,
      dataIndex: 'name',
      align: 'center',
      cell: (v, i, r) => (
        <>
          <Button type="primary" text onClick={() => handleCurCharge(r, 'rsPlay')}>{t`编辑`}</Button>
          <Divider direction="ver" />
          <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeleteState(i, 'rsPlay')}>{t`删除`}</Button>
        </>
      ),
    },
  ];
  const rsDetailColumns = [
    {
      title: t`序号`,
      dataIndex: 'id',
      align: 'center',
      cell: (v, i) => <span>{i + 1}</span>,
    },
    {
      title: t`事项`,
      dataIndex: 'name',
      width: 200,
      align: 'center',
    },
    {
      title: t`操作`,
      dataIndex: 'name',
      align: 'center',
      cell: (v, i, r) => (
        <>
          <Button type="primary" text onClick={() => handleCurCharge(r, 'rsDetail')}>{t`编辑`}</Button>
          <Divider direction="ver" />
          <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeleteState(i, 'rsDetail')}>{t`删除`}</Button>
        </>
      ),
    },
  ];

  const overrideModel = {
    extras: {
      label: t`拓展属性`,
      themeColor: {
        label: t`主题色`,
        value: {
          label: t`主题色`,
          ui: {
            renderer: () => (
              <div style={{ position: 'relative', display: 'inline-block', margin: 0, zIndex: 99999, marginTop: 3 }}>
                <div
                  color={color}
                  onClick={() => setVisible(!visible)}
                  style={{
                    width: 60,
                    height: 20,
                    border: '1px solid #ccc',
                    backgroundColor: color,
                    cursor: 'pointer',
                  }}
                />
                {
                  <ColorSelector
                    color={color}
                    className={styles.container}
                    style={{ position: 'absolute' }}
                    visible={visible}
                    localStorageKey={null}
                    showPipetteColor
                    // eslint-disable-next-line no-shadow
                    onChange={({ color }) => handleColorSelect(color)}
                    onVisibleChange={(v) => setVisible(v)}
                  />
                }
              </div>
            ),
          },
        },
      },
      scPropagationLanguage: {
        label: t`专线宣传语`,
        value: {
          label: t`专线宣传语`,
          ui: {
            renderer: () => (
              <>
                <Button type="primary" style={{ marginBottom: 10 }} onClick={() => handleAddState('sc')}>{t`添加宣传语`}</Button>
                <Table
                  hasBorder={false}
                  dataSource={state.sc}
                  columns={scColumns}
                  onRowClick={(_, index) => setIdx({ ...idx, sc: index })}
                />
              </>
            ),
          },
        },
      },
      busPropagationLanguage: {
        label: t`巴士宣传语`,
        value: {
          label: t`巴士宣传语`,
          ui: {
            renderer: () => (
              <>
                <Button type="primary" style={{ marginBottom: 10 }} onClick={() => handleAddState('bus')}>{t`添加宣传语`}</Button>
                <Table
                  hasBorder={false}
                  dataSource={state.bus}
                  columns={busColumns}
                  onRowClick={(_, index) => setIdx({ ...idx, bus: index })}
                />
              </>
            ),
          },
        },
      },
      rsPlayOrderCautionLanguage: {
        label: t`拼车下单界面注意事项`,
        value: {
          label: t`拼车下单界面注意事项`,
          ui: {
            renderer: () => (
              <>
                <Button type="primary" style={{ marginBottom: 10 }} onClick={() => handleAddState('rsPlay')}>{t`添加注意事项`}</Button>
                <Table
                  hasBorder={false}
                  dataSource={state.rsPlay}
                  columns={rsPlayColumns}
                  onRowClick={(_, index) => setIdx({ ...idx, rsPlay: index })}
                />
              </>
            ),
          },
        },
      },
      rsOrderDetailCautionLanguage: {
        label: t`拼车订单详情界面注意事项`,
        value: {
          label: t`拼车订单详情界面注意事项`,
          ui: {
            renderer: () => (
              <>
                <Button type="primary" style={{ marginBottom: 10 }} onClick={() => handleAddState('rsDetail')}>{t`添加注意事项`}</Button>
                <Table
                  hasBorder={false}
                  dataSource={state.rsDetail}
                  columns={rsDetailColumns}
                  onRowClick={(_, index) => setIdx({ ...idx, rsDetail: index })}
                />
              </>
            ),
          },
        },
      },
    },
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(theme, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleAddState = (type) => {
    const title = ['安全放心', '服务至上', '价格优惠', '效率保证', '遥遥领先', 'vip服务', '7x24客服'];
    // 生成1~6随机数
    const randomNumber = Math.floor(Math.random() * 6) + 1;
    const data = {
      id: new Date().getTime(),
      name: title[randomNumber],
    };
    setState((pre) => {
      const cloneData = { ...pre };
      cloneData[type].push(data);
      return cloneData;
    });
  };

  const handleDeleteState = (i, type) => {
    setState((pre) => {
      const arr = { ...pre };
      arr[type].splice(i, 1);
      return arr;
    });
  };

  const handleCurCharge = (values, type) => {
    setCurCharge({
      values,
      type,
    });
  };

  const chargeOnSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    const { type } = curCharge;
    const newInx = idx[type];
    setState((pre) => {
      const newCharge = { ...pre };
      newCharge[type][newInx] = values;
      return newCharge;
    });
    setCurCharge(false);
  };

  /**
   * @description 选择器颜色事件回调
   * @param {*} v
   */
  const handleColorSelect = (v) => {
    setColor(v);
    _.set(theme, 'extras.themeColor.value', v);
  };

  /**
   * @description 提交表单实现修改配置
   * @param {*} r formData
   */
  const handleSubmit = (values, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    _.set(theme, 'extras.scPropagationLanguage.value', JSON.stringify(state.sc));
    _.set(theme, 'extras.busPropagationLanguage.value', JSON.stringify(state.bus));
    _.set(theme, 'extras.rsPlayOrderCautionLanguage.value', JSON.stringify(state.rsPlay));
    _.set(theme, 'extras.rsOrderDetailCautionLanguage.value', JSON.stringify(state.rsDetail));
    onSubmit?.(theme);
  };
  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={theme}
      onChange={handleChange}
    >
      <FieldsGrid
        formData={theme}
        mode={modal[0]}
        columns={4}
        overrideModel={overrideModel}
        fields={[
          'appTitle', 'themeColor',
          'scSpecialLanguage',
          'busSpecialLanguage',
          'stationPropagationLanguage',
        ].map((n) => `extras.${n}.value`)}
      />
      <FieldsGrid
        formData={theme}
        mode={modal[0]}
        columns={3}
        overrideModel={overrideModel}
        fields={[
          'scPropagationLanguage',
          'busPropagationLanguage',
          'rsPlayOrderCautionLanguage',
          'rsOrderDetailCautionLanguage',
        ].map((n) => `extras.${n}.value`)}
      />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
      <Dialog
        visible={!!curCharge}
        onCancel={() => setCurCharge(false)}
        onClose={() => setCurCharge(false)}
        title={t`编辑内容`}
        style={{ width: '30%' }}
        footer={null}
      >
        <ChargeForm
          data={curCharge}
          onSubmit={(r, errors) => chargeOnSubmit(r, errors)}
          onCancel={() => setCurCharge(false)}
        />
      </Dialog>
    </Form>
  );
};

export default observer(Theme);
